// pages/profile/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickName: '',
    avatar: ''
  },
  onLoad() {
    const app = getApp()
    console.log(app);
    this.setData({
      avatar: app.userInfo.avatar,
      nickName: app.userInfo.nickName
    })
  },
  // 1.获取昵称
  getUserNickname(e) {
    console.log(e);
    this.updateUserInfo(e.detail.value)
  },
  // 2. 调接口把数据存在后台
  async updateUserInfo(nickName) {
    if (nickName === '') return
    // 调用接口更新个人信息
    const {
      code
    } = await wx.http.put('/userInfo', {
      nickName
    })
    this.setData({
      nickName
    })
  },
  // 获取头像
  getUserAvatar(e) {
    console.log(e.detail.avatarUrl);
    this.updateAvatar(e.detail.avatarUrl)
  },
  // 调接口把图片传到后台
  updateAvatar(avatar) {
    wx.uploadFile({
      url: wx.http.baseURL + '/upload', //仅为示例，非真实的接口地址
      filePath: avatar,
      name: 'file',
      formData: {
        'type': 'avatar'
      },
      header: {
        Authorization: 'Bearer ' + getApp().token
      },
      success: (res) => {
        // const data = res.data
        //do something
        console.log(res);
        const data = JSON.parse(res.data)
        console.log(data);
        if (data.code !== 10000) return wx.utils.toast('没上传成功,不要发违法图片')
        this.setData({
          avatar: data.data.url
        })
      }
    })
  }
})